﻿using Config;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEngine;

namespace DiverseStudents.Resource.Old
{
    //Resource/audios 
    internal class AudioLoader : MonoBehaviour
    {

        public static string path = "./Resource/Audios";

        public static void New()
        {
            var properties = typeof(Cfg).GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
            var acs = properties.Where(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericTypeDefinition() == typeof(Dictionary<,>) && x.PropertyType.GetGenericArguments()[1].Name == "AudioCfg");
            if (acs.Any())
            {
                var acm = (Dictionary<int, AudioCfg>)acs.First().GetValue(null);//
                if (acm != null)
                {
                    List<string> aus = new List<string>();
                    foreach (var a in acm)
                    {
                        aus.Add(a.Value.name);
                        //DLog.Log(a.Value.name);
                    }
                    var list = Load(aus);
                    foreach (var item in list)
                    {
                        if (acm.TryGetValue(item, out var ac))
                        {
                            //  Debug.Log(ac.name);
                        }
                    }
                }
                else
                {
                    DLog.Warring("AudioCfgMap Get failed");
                }
            }
            else
            {
                DLog.Warring("Not Find PropertyType fo Audio");
            }
        }

        private static List<int> Load(List<string> list)
        {
            var list2 = new List<int>();
            var info = Directory.CreateDirectory(path);
            if (!Directory.Exists(path))
            {
                return list2;
            }
            var files = info.GetFiles("*.*");
            var musicFileRegex = new Regex("\\.(mp3|wav|acc|flac|ogg|wma)$");
            foreach (var file in files)
            {
                string fileNameWithoutExtension = file.Name.Substring(0, file.Name.LastIndexOf('.'));
                var index = list.FindIndex(x => x == "Audios/" + fileNameWithoutExtension);
                if (index >= 0)
                {
                    if (!musicFileRegex.IsMatch(file.Extension.ToLower()))
                    {
                        continue;
                    }
                    DLog.Warring($"Load Audio file:{fileNameWithoutExtension}");
                    list2.Add(index);
                }
            }
            return list2;
        }

    }
}
